<script setup lang="ts">
import CustomNavbar from './components/CustomNavbar.vue'
import { getHomeBannerAPI, getHomeCategory, getHomeHot } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import { onRenderTriggered, ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import type { XtxGuessInstance } from '@/types/component'
import PageSkeleton from '@/pages/index/components/PageSkeleton.vue'
import { useGuessList } from '@/composables'

// 获取轮播图
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}

// 获取前台分类数据
const getHomeCategoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategory()
  getHomeCategoryList.value = res.result
}

// 热门推荐
const getHomeHotList = ref<HotItem[]>([])
const getHomeHotData = async () => {
  const res = await getHomeHot()
  getHomeHotList.value = res.result
}

// 滚动触底加载
/*const guessRef = ref<XtxGuessInstance>() // 获取组件实例
const onScrollTolower = () => {
  guessRef.value?.getMore()
}*/
const { guessRef, onScrolltolower } = useGuessList()

// 自定义下拉刷新被触发
const renderTriggered = ref(false)

const onRefresher = async () => {
  // 开启效果
  renderTriggered.value = true
  // 重置猜你喜欢数据
  guessRef.value?.resetData()
  // 加载数据
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    guessRef.value?.getMore(),
  ])
  // 关闭效果
  renderTriggered.value = false
}

// 是否加载中
const isLoading = ref(false)
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})
</script>

<template>
  <CustomNavbar />
  <scroll-view
    refresher-enabled
    :refresher-triggered="renderTriggered"
    @refresherrefresh="onRefresher"
    @scrolltolower="onScrolltolower"
    class="scroll"
    scroll-y
  >
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <XtxSwiper :list="bannerList" />
      <!--  分类面板-->
      <CategoryPanel :list="getHomeCategoryList" />
      <HotPanel :list="getHomeHotList" />
      <!--  猜你喜欢-->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scroll {
  flex: 1;
}
</style>
